//
//  AddViewController.m
//  geiTA
//
//  Created by 杨元龙 on 14-11-19.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "AddViewController.h"
#import "TextFiledCell.h"
#import "LableButtonCell.h"
#import "LableQradioButtonCell.h"
#import "RecordDataBase.h"
#import "RecordModel.h"
#import "mySinglietongClass.h"
@interface AddViewController ()<UITableViewDataSource, UITableViewDelegate,RadioButtonDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,assign)NSInteger i;
@property (nonatomic, assign)NSInteger a;
@property (nonatomic, assign) BOOL isFullScreen;
@end

@implementation AddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIColor *color = [UIColor colorWithRed:239.0f/255.0f green:238.0f/255.0f blue:244.0f/255.0f alpha:1.0f];
    [self.view setBackgroundColor:color];
    self.my = [mySinglietongClass shareManager];
      _a = 10;
    
    if (self.contentmodel == nil) {
        NSArray *arr = [NSArray arrayWithObjects:@"姓名",@"请输入姓名", nil];
        NSArray *arr1 = [NSArray arrayWithObjects:@"性别",@"", nil];
        NSArray *arr2 = [NSArray arrayWithObjects:@"纪念日",@"点击设置日期", nil];
        
        NSArray *arr3 = [NSArray arrayWithObjects:@"手机",@"请输入手机号", nil];
        NSArray *arr4 = [NSArray arrayWithObjects:@"关系",@"未设置关系", nil];
        NSArray *arr5 = [NSArray arrayWithObjects:@"提醒设置",@"请设置提醒日期", nil];
        NSArray *arr6 = [NSArray arrayWithObjects:@"备注",@"请填写备注", nil];
        
        NSMutableArray *array1 = [NSMutableArray arrayWithObjects:arr,arr1,arr2, nil];
        NSMutableArray *array2 = [NSMutableArray arrayWithObjects:arr3,arr4,arr5,arr6, nil];
        
        self.aray =[NSMutableArray arrayWithObjects:array1,array2, nil];

    }else
    {
     
        NSArray *arr = [NSArray arrayWithObjects:@"姓名",_contentmodel.name, nil];
        NSArray *arr1 = [NSArray arrayWithObjects:@"性别", _contentmodel.sex, nil];
        NSArray *arr2 = [NSArray arrayWithObjects:@"纪念日",_contentmodel.remindDate, nil];
        
        NSArray *arr3 = [NSArray arrayWithObjects:@"手机",_contentmodel.phone, nil];
        NSArray *arr4 = [NSArray arrayWithObjects:@"关系", _contentmodel.relationship, nil];
        NSArray *arr5 = [NSArray arrayWithObjects:@"提醒设置",@"请设置提醒日期", nil];
        NSArray *arr6 = [NSArray arrayWithObjects:@"备注",_contentmodel.note, nil];
        
        NSMutableArray *array1 = [NSMutableArray arrayWithObjects:arr,arr1,arr2, nil];
        NSMutableArray *array2 = [NSMutableArray arrayWithObjects:arr3,arr4,arr5,arr6, nil];
        
        self.aray =[NSMutableArray arrayWithObjects:array1,array2, nil];
    }
    
    
    
    
    
    [self createTableView];
    [self createVIew];
    [self createBarButtn];

    
}


- (void)createBarButtn
{
    UIButton *button =[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    [button setTitle:@"完成" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *bar =[[UIBarButtonItem alloc]initWithCustomView:button];
    [self.navigationItem setRightBarButtonItem:bar];
    
    
    
    
}
- (void)buttonAction:(id)sender
{
    
    UITextField *field10 =(UITextField *)[self.view viewWithTag:10];
    UITextField *field11 =(UITextField *)[self.view viewWithTag:11];
    UITextField *field12 =(UITextField *)[self.view viewWithTag:12];
    UITextField *field14 =(UITextField *)[self.view viewWithTag:14];
   

    self.model = [[RecordModel alloc]init];
    _model.recordid =_my.flag;
    _my.flag ++;
    _model.name = field10.text;
    _model.phone = field11.text;
    _model.relationship = field12.text;
    _model.note = field14.text;
    
    if (_my.selectPage == 1){
    _model.remindDate = _dateStr;
    }
    else{
        if (_dateStr ==nil) {
            _model.remindDate = _contentmodel.remindDate;
        }else
        {
            _model.remindDate = _dateStr;
        }
    }
    if (_tags == 100) {
        _model.sex = @"男";
        
    }
    else{
        _model.sex = @"女";
    }
    
   if (_my.selectPage == 1) {
    //data传到数据库
    if ([_model.name  isEqual: @""]) {
        
        /************************* 提示添加失败 请输入姓名**********************************/
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请输入姓名" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [self.view addSubview:alert];
        [alert show];
        
        
    }else if (_dateStr == nil ){
        /*******************  提示 添加失败请输入日期***************************/
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请选择日期" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [self.view addSubview:alert];
        [alert show];
        
    }else{
        [RecordDataBase insertWithModel:_model];
        //返回界面
        [self.navigationController popViewControllerAnimated:YES];
        
    }
}
   else{
    _model.recordid = _contentmodel.recordid;
    [RecordDataBase updateWithModel:_model];
    [self.delegate huidiao:_model];
    //返回界面
    [self.navigationController popViewControllerAnimated:YES];
}
}



- (void)createVIew
{

    self.photoImageView  = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/32 * 11,10 , self.view.frame.size.width/16 * 5, self.view.frame.size.height/5)];
    [_photoImageView setBackgroundColor:[UIColor yellowColor]];
    
     if (_contentmodel != nil) {
         NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld.png",(long)_contentmodel.recordid]];
         UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
         [_photoImageView setImage:savedImage];

    }
    
    
    [self.view addSubview:_photoImageView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseImage:)];
    [_photoImageView setUserInteractionEnabled:YES];
    [_photoImageView addGestureRecognizer:tap];

    
    
    //模糊界面视图
    self.shadowView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [_shadowView setBackgroundColor:[UIColor blackColor]];
    _shadowView.alpha = 0.3;
    //隐藏
    _shadowView.hidden = YES;
    
    [self.view addSubview:_shadowView];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(shadowViewAction)];
    [_shadowView addGestureRecognizer:tap1];
  
    
}
-(void)shadowViewAction
{
    
    [UIView animateWithDuration:1.0f animations:^{
        
        [_dateview setFrame:CGRectMake(0,self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height/3)];
        
    }];
    _i =1;
    _shadowView.hidden =YES;
    
}

- (void)buttonCtion:(id)sender
{
    
       _i = 1;
    [self createTimeSeleCtor];
    _shadowView.hidden =NO;
    
    
}
//时间选择期
- (void)createTimeSeleCtor
{
    
    
    
    if (_i == 1) {
        
        
        self.dateview = [[UIView alloc]initWithFrame:CGRectMake(0,self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height)];
        [_dateview setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:_dateview];
        //日期
        UIDatePicker *date = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 30, 0, 0)];
        [date setLocale:[NSLocale localeWithLocaleIdentifier:@"zh-CN"]];

        date.datePickerMode = UIDatePickerModeDate;
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy年MM月dd日"];
        
        NSDate *currDate = [date date];
        self.curr =[formatter stringFromDate:currDate];
        [_dateview addSubview:date];
        
        [date addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
        
        
        
        
        
        //工具条
        UIToolbar *tool = [[UIToolbar alloc] init];
        [tool setFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
        [tool setBackgroundColor:[UIColor whiteColor]];
        
        [_dateview addSubview:tool];
        
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 50, 0, 50, 40)];
        [button setTitle:@"完成" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        [tool addSubview:button];
        
        
        [UIView animateWithDuration:1.0f animations:^{
            
            
            
            [_dateview setFrame:CGRectMake(0,self.view.frame.size.height -280, self.view.frame.size.width, self.view.frame.size.height)];
            
        }];
        
        _i  =2;
    }
    
    
}


//传值
- (void)dateChanged:(id)sender
{
    
    
    UIDatePicker *dataPicker_one = (UIDatePicker *)sender;
    NSDate *date_one = dataPicker_one.date;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    
    self.dateStr = [formatter stringFromDate:date_one];
    
    NSLog(@"%@",self.dateStr);
    [formatter release];
    
}
- (void)click:(id)sender
{
    if (self.dateStr  == nil ) {
          _dateStr = _curr;
    }
    
    [_cell.dateButton  setTitle:_dateStr forState:UIControlStateNormal];
    [_cell.dateButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    
    [UIView animateWithDuration:0.5f animations:^{
        
        [_dateview setFrame:CGRectMake(0,self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height/3)];
        
    }];
    _i =1;
    _shadowView.hidden =YES;
    
    
}


#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    
    
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:YES];
    
}
#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        if ( self.contentmodel == nil) {
        [self saveImage:image withName:[NSString stringWithFormat:@"%ld.png",(long)_my.flag]];
        
        NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld.png",(long)_my.flag]];
        UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
        _isFullScreen = NO;
        [self.photoImageView setImage:savedImage];
        
        self.photoImageView.tag = 51;


    }else
    {
        [self saveImage:image withName:[NSString stringWithFormat:@"%ld.png",(long)_contentmodel.recordid]];
        
        NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld.png",(long)_contentmodel.recordid]];
         UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
        _isFullScreen = NO;
        [self.photoImageView setImage:savedImage];
        
        self.photoImageView.tag = 51;

        
    }
    
    
   
//    }
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark - actionsheet delegate
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    
    if (actionSheet.tag == 255) {
        
        NSUInteger sourceType = 0;
        
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            switch (buttonIndex) {
                case 0:
                    // 取消
                    return;
                case 1:
                    // 相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                    
                case 2:
                    // 相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
            }
        }
        else {
            if (buttonIndex == 0) {
                
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        
        imagePickerController.delegate = self;
        
        imagePickerController.allowsEditing = YES;
        
        imagePickerController.sourceType = sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:^{}];
        
        [imagePickerController release];
    }
}
- (void)chooseImage:(id)sender {
    UITextField *field10 =(UITextField *)[self.view viewWithTag:10];
    if ([field10.text  isEqual: @""]) {
        /***************   提示 没有添加名字不能添加照片*********************/
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请先填写姓名" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [self.view addSubview:alert];
        [alert show];
        
        
    }else
    {

    UIActionSheet *sheet;
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
    }
    else {
        
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
    }
    
    sheet.tag = 255;
    
    [sheet showInView:self.view];
    }
    
}


#pragma mark -
#pragma mark TableView
- (void)createTableView
{
    UITableView *table =[[UITableView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height/5 +20, self.view.frame.size.width, self.view.frame.size.height/ 6 * 5 -113) style:UITableViewStyleGrouped];
    //禁止滚动
    table.scrollEnabled = YES;

    
    table.dataSource =self;
    table.delegate =self;
    table.rowHeight = self.view.frame.size.height/13;
    
    [self.view addSubview:table];
}
//section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return [_aray count];
}

//cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *arr = [_aray objectAtIndex:section];
    return [arr count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    

    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 1) {
            static NSString *pool3 =@"ok3";
            self.cell1 = [tableView dequeueReusableCellWithIdentifier:pool3];
            if (!_cell1) {
                _cell1 = [[LableQradioButtonCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:pool3];
            }
            //取消cell的选中状态
            _cell1.selectionStyle = UITableViewCellEditingStyleNone;
            
            
            NSMutableArray *arr = [_aray objectAtIndex: indexPath.section];
            NSMutableArray *ar= [arr objectAtIndex:indexPath.row];
            _cell1.nameLable.text = [ar objectAtIndex:0];
            _cell1.radio.delegate =self;
        
            
            return _cell1;
            
            
        }
        
        
        if (indexPath.row == 2) {
            static NSString *pool2 =@"ok2";
            _cell = [tableView dequeueReusableCellWithIdentifier:pool2];
            if (!_cell) {
                _cell = [[LableButtonCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:pool2];
            }
            //取消cell的选中状态
            _cell.selectionStyle = UITableViewCellEditingStyleNone;
            
            
            NSMutableArray *arr = [_aray objectAtIndex: indexPath.section];
            NSMutableArray *ar= [arr objectAtIndex:indexPath.row];
            
            _cell.nameLable.text = [ar objectAtIndex:0];
            [_cell.dateButton setTitle:[ar objectAtIndex:1] forState:UIControlStateNormal];
            
            if (_contentmodel  == nil) {
                 [_cell.dateButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            }else
            {
                 [_cell.dateButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            }
            
           
              [_cell.dateButton addTarget:self action:@selector(buttonCtion:) forControlEvents:UIControlEventTouchUpInside];
            
            
            return _cell;

            
        }
    }
    static NSString *pool =@"ok1";
    TextFiledCell *cell = [tableView dequeueReusableCellWithIdentifier:pool];
    if (!cell) {
        cell = [[TextFiledCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:pool];
    }
    //取消cell的选中状态
    cell.selectionStyle = UITableViewCellEditingStyleNone;
    
    
    NSMutableArray *arr = [_aray objectAtIndex: indexPath.section];
    NSMutableArray *ar= [arr objectAtIndex:indexPath.row];
    
    cell.nameLable.text = [ar objectAtIndex:0];
    if (_contentmodel == nil) {
        cell.field.placeholder = [ar objectAtIndex:1];
    }else
    {
        cell.field.text = [ar objectAtIndex:1];
    }

  
    cell.field.tag = _a;
    _a ++;
    
    
    return cell;
}


-(void)chuanzhi:(RecordModel *)model1
{
    self.contentmodel = model1;
}

//单选按钮回调方法
-(void)changeSender:(NSInteger)tag
{
    _tags = tag;
}

@end
